package com.micro.service.gateway.web.tps;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class DefaultTPSLimiter implements TPSLimiter {

    private final ConcurrentMap<String, StatItem> stats = new ConcurrentHashMap<>();

    private int rate=5;

    public int getRate() {
        return rate;
    }

    public void setRate(int rate) {
        this.rate = rate;
    }

    @Override
    public boolean isAllowable(HttpServletRequest httpServletRequest) {
        //默认一秒允许5次请求
        long interval = 1000;

        String sessionIdAndReqURI = httpServletRequest.getRequestedSessionId() + ":" + httpServletRequest.getRequestURI();
        StatItem statItem = stats.get(sessionIdAndReqURI);
        if (statItem == null) {
            stats.putIfAbsent(sessionIdAndReqURI, new StatItem(sessionIdAndReqURI, rate, interval));
            statItem = stats.get(sessionIdAndReqURI);
        }
        return statItem.isAllowable(httpServletRequest);
    }

    public void timerClear(){
        for (String sessionIdAndReqURI:stats.keySet()) {
            StatItem statItem = stats.get(sessionIdAndReqURI);
            if (statItem != null) {
                if(statItem.isOutOfDate()){
                    stats.remove(sessionIdAndReqURI);
                }
            }
        }
    }

    public ConcurrentMap<String, StatItem> getStats() {
        return stats;
    }
}
